#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# QQ: 34538980@qq.com
# Jekkay Hu, 2013.5.5
# ///////////////////////////////////////////////////////////////////
#                            _ooOoo_                               //
#                           o8888888o                              //
#                           88" . "88                              //
#                           (| ^_^ |)                              //
#                           O\  =  /O                              //
#                        ____/`---'\____                           //
#                      .'  \\|     |//  `.                         //
#                     /  \\|||  :  |||//  \                        //
#                    /  _||||| -:- |||||-  \                       //
#                    |   | \\\  -  /// |   |                       //
#                    | \_|  ''\---/''  |   |                       //
#                    \  .-\__  `-`  ___/-. /                       //
#                  ___`. .'  /--.--\  `. . ___                     //
#                ."" '<  `.___\_<|>_/___.'  >'"".                  //
#              | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 //
#              \  \ `-.   \_ __\ /__ _/   .-` /  /                 //
#        ========`-.____`-.___\_____/___.-`____.-'========         //
#                             `=---='                              //
#        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
#             佛祖保佑       永无BUG        运行正常                   //
#     -------------------------------------------------------      //
#               QQ: 34538980@qq.com                                //
#               博客: http://www.easysb.cn                          //
#               Jekkay Hu, 2013.5.5                                //
# ///////////////////////////////////////////////////////////////////
#
#  将工作线程池的扫描结果同步到数据库中
#
import logging
import time
from scan.base_db_op_thread import BaseDBOpThread

SQL_QUERY_DOMAIN = 'SELECT * FROM `domain` WHERE `domain`=%(domain)s'
SQL_INSERT_DOMAIN = ('INSERT INTO `domain`(`id`, `domain`, `code`, `title`, `is_http`, `is_https`, '
                     '`scan`, `create_time`) VALUES'
                     '(%(id)s,%(domain)s,%(code)s,%(title)s,%(is_http)s,%(is_https)s,%(scan)s,%(create_time)s)')
SQL_UPDATE_DOMAIN = ('UPDATE `domain` SET `code`=%(code)s, `title`=%(title)s, `is_http`=%(is_http)s,'
                     '`is_https`=%(is_https)s,`scan`=%(scan)s,`create_time`=%(create_time)s '
                     'WHERE `id`=%(id)s'
                     )


class DomainSyncThread(BaseDBOpThread):
    def __init__(self, result_domain_queue):
        super(DomainSyncThread, self).__init__()
        self.result_domain_queue = result_domain_queue

    def work_loop(self):
        self.is_working = False
        if self.result_domain_queue.qsize() <= 0:
            time.sleep(0.1)
            return
        domain = self.result_domain_queue.get()
        if not domain:
            return
        self.is_working = True
        # 查询之前的
        origin = self.db.query(SQL_QUERY_DOMAIN, domain.__dict__)
        origin = origin[0] if len(origin) > 0 else None
        if not origin:
            self.db.execute(SQL_INSERT_DOMAIN, domain.__dict__)
            logging.info('> insert new domain [ %s ]' % domain.domain)
        elif (domain.title and origin['title'] != domain.title) or origin['is_http'] < domain.is_http \
                or origin['is_https'] < domain.is_https or origin['scan'] < domain.scan:
            if domain.title:
                origin['title'] = domain.title
            origin['is_http'] = 1 if domain.is_http + origin['is_http'] > 0 else 0
            origin['is_https'] = 1 if domain.is_https + origin['is_https'] > 0 else 0
            if origin['scan'] < domain.scan:
                origin['scan'] = domain.scan
            self.db.execute(SQL_UPDATE_DOMAIN, origin)
            logging.info('> update domain info [ %s ]' % domain.domain)
